//
//  UserDataEditViewController.m
//  Molian
//
//  Created by 胡津 on 15/4/2.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//
#define chooseBtnTag 1000

#import "UserDataEditViewController.h"
#import "UserDataEditCell.h"
#import "ZHPickView.h"
#import "UserTagsViewController.h"
#import "UserDataEditLabelViewController.h"
#import "UserDataEditPhoto.h"
#import "UserDateEditSeriesViewController.h"
#import "UserVoiceViewController.h"
#import "VoiceCell.h"

#import "MLAudioPlayer.h"
#import "AmrPlayerReader.h"
#import <CommonCrypto/CommonDigest.h>
#import "UserDataEditTagCell.h"
#import "JCTagListView.h"

@interface UserDataEditViewController ()<UITableViewDelegate,UITableViewDataSource,ZHPickViewDelegate,UserDataEditLabelDelegate,UserTagsDelegate,UserDateEditSeriesDelegate,UserDataEditPhotoDelegate,UserVoiceViewControllerDelegate>

//视图列表
@property (nonatomic, strong)UITableView *tableView;
@property BOOL infoType;
@property (nonatomic, strong)NSArray *userInfoArr;
@property (nonatomic, strong)NSMutableArray *userDataArr;

@property(nonatomic,strong)ZHPickView *pickview;
@property(nonatomic,strong)NSIndexPath *indexPath;

@property BOOL saveUserBool;//资料保存判断

//输入框视图
@property(nonatomic,strong)UserDataEditLabelViewController *EditLabelVC;
//系列选择
@property(nonatomic,strong)UserDateEditSeriesViewController *EditSeriesVC;

/*
 * 数据
 */
@property (strong, nonatomic)MLGallery *myGallery;
@property (strong, nonatomic) MLUser *currentUser;

@property (strong, nonatomic)NSArray *likeArr;//喜欢的
@property (strong, nonatomic)NSArray *languageArr;//语言
@property (strong, nonatomic)NSArray *salutationMeArr;//叫我
@property (strong, nonatomic)NSArray *special;//特技
@property (strong, nonatomic)NSArray *wanArr;//我想
@property (strong, nonatomic)NSArray *idealArr;//理想的你

@property (strong, nonatomic)NSDate *birthdayDate;//生日
@property (strong, nonatomic)NSString *location_province;//省
@property (strong, nonatomic)NSString *location_city;//市
@property NSInteger height;//身高
@property (strong, nonatomic)NSString *figure;//体型
@property NSInteger weight;//体重

@property (strong, nonatomic)NSString *interestTopic;//兴趣话题


// 音频播放
@property (nonatomic, strong) MLAudioPlayer *player;
@property (nonatomic, strong) AmrPlayerReader *amrReader;

@property NSInteger voicePlayIndex;

@property NSInteger voicePlayStatus;

// 共享的音频播放计时器
@property (nonatomic, strong) NSTimer *updateAudioUITimer;
//
@property (nonatomic, strong)UserDataEditPhoto *userPhoto;


@property CGFloat h1;//我想
@property CGFloat h2;//理想的你
@property CGFloat h3;//特技
@property CGFloat h4;//喜欢

@end

@implementation UserDataEditViewController
{
    BOOL f5Bool;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [_pickview remove];
    // 关闭语音播放
    [self.player stopPlaying];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self userDataCompleteThedegree];
    [self.tableView reloadData];
    f5Bool = NO;
    
//    for (int i = 1; i<5; i++) {
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
//        UserDataEditTagCell *tagCell =(UserDataEditTagCell *) [self.tableView cellForRowAtIndexPath:indexPath];
//        if (tagCell) {
//            
//            if ([tagCell.titleLabel.text isEqualToString:@"我想"]) {
//                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                    self.h1 = tagCell.tagListView.collectionView.contentSize.height;
//                }
//            }else if ([tagCell.titleLabel.text isEqualToString:@"理想的你"]){
//                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                    self.h2 = tagCell.tagListView.collectionView.contentSize.height;
//                }
//            }else if ([tagCell.titleLabel.text isEqualToString:@"特技"]){
//                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                    self.h3 = tagCell.tagListView.collectionView.contentSize.height;
//                }
//            }else if ([tagCell.titleLabel.text isEqualToString:@"喜欢"]){
//                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
//                    self.h4 = tagCell.tagListView.collectionView.contentSize.height;
//                }
//            }
//            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
//        }
//    }
   
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    for (int i = 1; i<5; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
        UserDataEditTagCell *tagCell =(UserDataEditTagCell *) [self.tableView cellForRowAtIndexPath:indexPath];
        if (tagCell) {
            
            if ([tagCell.titleLabel.text isEqualToString:@"我想"]) {
                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                    self.h1 = tagCell.tagListView.collectionView.contentSize.height;
                }
            }else if ([tagCell.titleLabel.text isEqualToString:@"理想的你"]){
                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                    self.h2 = tagCell.tagListView.collectionView.contentSize.height;
                }
            }else if ([tagCell.titleLabel.text isEqualToString:@"特技"]){
                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                    self.h3 = tagCell.tagListView.collectionView.contentSize.height;
                }
            }else if ([tagCell.titleLabel.text isEqualToString:@"喜欢"]){
                if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                    self.h4 = tagCell.tagListView.collectionView.contentSize.height;
                }
            }
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}
-(void)leftItem
{
    if (self.saveUserBool == YES) {
        HUD * hud = [[HUD alloc]init];
        [hud HUDImage:nil Title:@"资料已做修改" Content:@"是否不保存退出?" CANCEL:@"是的" Confirm:@"取消"];
        hud.Cancel = ^{
            [self.navigationController popViewControllerAnimated:YES];
        };
        hud.Confirm = ^{
            
        };
        [self.view addSubview:hud];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    [_pickview remove];
}

-(void)initArr
{
    //标签数组
    self.likeArr = [[NSArray alloc]init];
    self.languageArr = [[NSArray alloc]init];
    self.salutationMeArr = [[NSArray alloc]init];
    
    //cell标题
    self.userInfoArr = [NSMutableArray arrayWithArray:@[@[@"昵称",@"年龄",@"城市"],@[@"个人签名", @"声线", @"我属于", @"叫我"], @[@"兴趣话题",@"我想",@"理想的你",@"特技",@"喜欢"],@[@"外貌",@"职业",@"语言"]]];
    
    //数据接入
    self.birthdayDate = self.currentUser.birthday ;//生日时间
    self.location_province = self.currentUser.location_province;//省份
    self.location_city = self.currentUser.location_city;//城市
    self.figure = self.currentUser.figure ? self.currentUser.figure :@"";//体型
    self.weight = self.currentUser.weight;//体重
    self.height = self.currentUser.height;//身高
    self.likeArr = self.currentUser.like_tags;//喜欢的
    self.languageArr = self.currentUser.language;//会的语言
    self.special = self.currentUser.special;
    self.wanArr = self.currentUser.want_tags;
    self.idealArr = self.currentUser.ideal_tags;
    self.interestTopic = self.currentUser.interestTopic;
    
    self.salutationMeArr = self.currentUser.called_tags;
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    
    NSString *languagestr = [[NSString alloc]init];
    for (int i = 0 ; i < [self.languageArr count]; i++) {
        if (i == [self.languageArr count]-1) {
            languagestr = [languagestr stringByAppendingString:[NSString stringWithFormat:@"%@",[self.languageArr objectAtIndex:i]]];
        }else{
            languagestr = [languagestr stringByAppendingString:[NSString stringWithFormat:@"%@、",[self.languageArr objectAtIndex:i]]];
        }
    }
    
    NSString *salutationMeStr = [[NSString alloc]init];
    for (int i = 0 ; i < [self.salutationMeArr count]; i++) {
        if (i == [self.salutationMeArr count]-1) {
            salutationMeStr = [salutationMeStr stringByAppendingString:[NSString stringWithFormat:@"%@",[self.salutationMeArr objectAtIndex:i]]];
        }else{
            salutationMeStr = [salutationMeStr stringByAppendingString:[NSString stringWithFormat:@"%@、",[self.salutationMeArr objectAtIndex:i]]];
        }
    }
    
    self.userDataArr = [NSMutableArray arrayWithArray:@[[@[[NSString stringWithFormat:@"%@",self.currentUser.nickname], [dateFormatter stringFromDate:self.birthdayDate], [NSString stringWithFormat:@"%@",self.currentUser.location_city]]mutableCopy],
                                                        [@[[NSString stringWithFormat:@"%@",self.currentUser.intro], @"声线", [NSString stringWithFormat:@"%@",self.currentUser.belong], [NSString stringWithFormat:@"%@",salutationMeStr]]mutableCopy], [@[[NSString stringWithFormat:@"%@",self.interestTopic?self.interestTopic:@""],@"",@"",@"",@""]mutableCopy],[@[[NSString stringWithFormat:@"%@",self.figure],[NSString stringWithFormat:@"%@",self.currentUser.job? self.currentUser.job:@""],[NSString stringWithFormat:@"%@",languagestr]]mutableCopy]]];
    [self.tableView setContentOffset:CGPointMake(0, 2000)animated:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView setContentOffset:CGPointMake(0, -64)animated:NO];
    });
    [self.tableView reloadData];
    
}
- (void)changePhone
{
    [self userDataCompleteThedegree];
    [self uploadingUserDataChange];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.changeUserData = NO;
    // Do any additional setup after loading the view.
    self.title = @"资料编辑";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    self.currentUser = [MLUser currentUser];
    f5Bool = NO;
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveUserInfo)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIBarButtonItem *leftItem  = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItem)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.saveUserBool = NO;
    
    //初始化数组数据咯
    [self initArr];
    // 初始化音频
    [self initAudioReader];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    
    
    // 获取相册内容
    AVQuery *galleryQuery = [MLGallery query];
    [galleryQuery whereKey:@"belong_to" equalTo:[MLUser currentUser]];
    [galleryQuery includeKey:@"images"];
    [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        self.myGallery = (MLGallery *)object;
        if (!self.myGallery) {
            // 找不到,创建新相册
            self.myGallery = [MLGallery object];
            self.myGallery.name = @"default gallery";
            self.myGallery.images = @[];
            self.myGallery.belong_to = [MLUser currentUser];
            self.myGallery.intro = @"";
            self.userPhoto = [[UserDataEditPhoto alloc]initWithFrame:CGRectMake(-1, -((DeviceWidth/2.5)+20), DeviceWidth, (DeviceWidth/2.5)+10)];
            self.userPhoto.delegate = self;
            _userPhoto.Gallery = self.myGallery;
            
            
            _userPhoto.photoEdit = YES;
            [_userPhoto setUpPhotoView];
            [self.tableView addSubview:_userPhoto];
            //            self.tableView.contentInset = UIEdgeInsetsMake((DeviceWidth/2.5)+30, 0, 0, 0);//偏移量
            
        } else {
            self.userPhoto = [[UserDataEditPhoto alloc]initWithFrame:CGRectMake(-1, -((DeviceWidth/2.5)+20), DeviceWidth, (DeviceWidth/2.5)+10)];
            self.userPhoto.delegate = self;
            _userPhoto.Gallery = self.myGallery;
            _userPhoto.photoEdit = YES;
            [_userPhoto setUpPhotoView];
            [self.tableView addSubview:_userPhoto];
            //            self.tableView.contentInset = UIEdgeInsetsMake((DeviceWidth/2.5)+30, 0, 0, 0);//偏移量
            
        }
        self.tableView.tableHeaderView = _userPhoto;
        
        [self.tableView reloadData];
        //资料完成度检查
        [self userDataCompleteThedegree];
    }];
    
    
    //文本输入
    self.EditLabelVC = [[UserDataEditLabelViewController alloc]init];
    self.EditLabelVC.Delegate = self;
    //系列
    self.EditSeriesVC = [[UserDateEditSeriesViewController alloc]init];
    self.EditSeriesVC.Delegate = self;
    
    //完成度view
    UIView *HeaderView = [[UIView alloc] initWithFrame:CGRectMake(-1, (DeviceWidth/2.5)+30, DeviceWidth+2, 50)];
    HeaderView.backgroundColor = [UIColor whiteColor];
    HeaderView.layer.borderWidth = 0.3;
    HeaderView.layer.borderColor = RGBA(225, 225, 225, 1).CGColor;
    [self.tableView addSubview:HeaderView];
    
    //资料完整度
    UILabel *completenessLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, 100, 30)];
    completenessLabel.text = @"资料完整度";
    completenessLabel.font = [UIFont fontWithName:FontName size:15];
    [HeaderView addSubview:completenessLabel];
    
    //资料不完整去口袋恋人的都是耍流氓
    UILabel *PromptLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 30, DeviceWidth-40, 20)];
    PromptLabel.text = @"资料完整才能更容易吸引恋人喜欢哦";
    PromptLabel.font = [UIFont fontWithName:FontName size:11];
    PromptLabel.textColor = [UIColor grayColor];
    [HeaderView addSubview:PromptLabel];
    
    //进度条
    for (int i=0; i<2; i++) {
        UIView *Line = [[UIView alloc]initWithFrame:CGRectMake(110, 12.5, DeviceWidth-150, 10)];
        Line.backgroundColor = [UIColor grayColor];
        Line.clipsToBounds = YES;
        Line.tag = i + 100;
        [Line.layer setCornerRadius:5];
        [HeaderView addSubview:Line];
        if (i == 1) {
            UIView *Line1 = (UIView *)[self.view viewWithTag:100];
            [Line1 addSubview:Line];
            Line.backgroundColor = APPCOLOR(1);
            Line.frame = CGRectMake(0, 0, 0, 10);
        }
    }
    
    UILabel *completeness = [[UILabel alloc]initWithFrame:CGRectMake(DeviceWidth-40, 5, 40, 30)];
    completeness.textAlignment = NSTextAlignmentCenter;
    completeness.textColor = [UIColor lightGrayColor];
    completeness.text = @"00%";
    completeness.tag = 200;
    completeness.font = [UIFont fontWithName:FontName size:11];
    [HeaderView addSubview:completeness];
    
    [self.tableView reloadData];
    
}

// 保存更新后的用户资料
- (void)saveUserInfo {
    // 保存用户资料
    if ([self.userDataArr[0][0] isEqualToString:@""]) {
        [HUD Prompt:@"昵称不能为空"];
        return;
    }else{
        NSString *str = self.userDataArr[0][0];
        if (str == nil||str == NULL|| [str isKindOfClass:[NSNull class]]||[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
            [HUD Prompt:@"昵称不能全为空格"];
             return;
        }
    }
    //说明用户更改信息了
    //发送透传通知好友,更新信息
    //发送透传
    
    
    [[EaseMob sharedInstance].chatManager setApnsNickname:self.currentUser.nickname];
    BOOL changeNickname;
    if ([self.currentUser.nickname isEqualToString:self.userDataArr[0]] ) {
        changeNickname = NO;
    }else{
        changeNickname = YES;
    }
    
    //个人资料
    self.currentUser.nickname = self.userDataArr[0][0];
    
    
    if (self.currentUser.nickname&&[self.currentUser.nickname rangeOfString:@"口袋君"].location != NSNotFound) {
        [HUD Prompt:@"昵称里面不能包含口袋君"];
        return;
    }
    
    self.currentUser.birthday = self.birthdayDate;
    self.currentUser.location_province = self.location_province;
    self.currentUser.location_city = self.location_city;
    
    self.currentUser.intro = self.userDataArr[1][0];
    self.currentUser.belong = self.userDataArr[1][2];
    self.currentUser.called_tags = self.salutationMeArr;
    self.currentUser.like_tags = self.likeArr;
    
    self.currentUser.job = self.userDataArr[3][1];
    self.currentUser.figure = self.figure;
    self.currentUser.language = self.languageArr;
    self.currentUser.special = self.special;
    //兴趣话题
    self.currentUser.interestTopic = self.interestTopic;
    self.currentUser.want_tags = self.wanArr;
    self.currentUser.ideal_tags = self.idealArr;
    [self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            if (changeNickname) {
                [Utils changeUserDataSendUsers];
            }
           
            [self uploadingUserDataChange];
            
            self.returnSave();
            [self.navigationController popViewControllerAnimated:YES];
            [HUD Prompt:@"保存成功"];
        }else{
            [HUD Prompt:[NSString stringWithFormat:@"%@",@"网络异常"] ];
            return ;
        }
    }];
    
}
- (void)quit:(saveQuit)saveQuit
{
    self.returnSave = saveQuit;
}
//保存用户资料
- (void)uploadingUserDataChange
{
    MLUser *user = [MLUser currentUser];
    if (user.type != MLUserType_NORMAL) {
        if (self.saveUserBool) {
            if (self.changeUserData == NO) {
                self.changeUserData = YES;
                MLInfoChangeNotify *infoCN = [MLInfoChangeNotify object];
                if ([MLUser currentUser].status == MLUserStatus_WARNING) {
                    infoCN.status = MLInfoChangeNotifyStatus_Recheck;
                }else{
                    infoCN.status = MLInfoChangeNotifyStatus_Wait;
                }
                infoCN.user = user;
                [infoCN saveInBackground];
            }
        }
    }
    
}

# pragma mark - tableview delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserDataEditCell *cell = nil;
    VoiceCell *voiceCell = nil;
    UserDataEditTagCell *tagCell = nil;
    if (indexPath.section == 0 ||indexPath.section == 1||indexPath.section ==3||(indexPath.section == 2&&indexPath.row == 0)) {
        static  NSString *CellIdentifier = @"UserDataCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (cell == nil) {
            cell = [[UserDataEditCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
        
        //标题设置
        cell.titleLabel.text = self.userInfoArr[indexPath.section][indexPath.row];
        //如果数据是数组则拆分出来拼接成字符串
        cell.contentLabel.text = self.userDataArr[indexPath.section][indexPath.row];
        
        if ([self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"职业"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"个人签名"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"兴趣话题"]) {
            cell.contentLabel.frame = CGRectMake(90, 0, DeviceWidth-120, [Utils LabeSizeLabelheight:self.userDataArr[indexPath.section][indexPath.row] Font:[UIFont fontWithName:FontName size:14]].height+(50-16.023438));
        }else{
            cell.contentLabel.frame = CGRectMake(90, 0, DeviceWidth-120, 50);
        }
        if (indexPath.section == 1 && indexPath.row ==1) {
            
            static  NSString *CellIdentifier = @"VoiceCell";
            voiceCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if  (voiceCell == nil) {
                voiceCell = [[VoiceCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            }
            voiceCell.titleLabel.text = self.userInfoArr[indexPath.section][indexPath.row];
            if (self.voiceArray.count != 0) {
                MLVoice *voice = self.voiceArray[0];
                [voiceCell.voiceBtn setTitle:!(long)voice.time ? @"":[NSString stringWithFormat:@"%ld\"",(long)voice.time] forState:UIControlStateNormal];
                [voiceCell.voiceBtn addTarget:self action:@selector(playVoice:) forControlEvents:UIControlEventTouchUpInside];
                voiceCell.voiceBtn.tag = indexPath.row;
                voiceCell.voiceBtn.hidden = NO;
            }else{
                voiceCell.voiceBtn.hidden = YES;
            }
            return voiceCell;
        }
        
        return cell;
    }else{
        NSString *CellIdentifier =[NSString stringWithFormat:@"cell%@",self.userInfoArr[indexPath.section][indexPath.row]];
        tagCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (tagCell == nil) {
            tagCell = [[UserDataEditTagCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        tagCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
        
        tagCell.titleLabel.text = self.userInfoArr[indexPath.section][indexPath.row];
        if ([tagCell.titleLabel.text isEqualToString:@"我想"]){
            tagCell.tagListView.canRemoveTags = NO;
            [tagCell.tagListView.tags setArray:self.wanArr];
            [tagCell.tagListView.collectionView reloadData];
            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                self.h1 = tagCell.tagListView.collectionView.contentSize.height;
            }
            
        }else if ([tagCell.titleLabel.text isEqualToString:@"理想的你"]){
            tagCell.tagListView.canRemoveTags = NO;
            [tagCell.tagListView.tags setArray:self.idealArr];
            [tagCell.tagListView.collectionView reloadData];
            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                self.h2 = tagCell.tagListView.collectionView.contentSize.height;
            }
            
        }else if ([tagCell.titleLabel.text isEqualToString:@"特技"]) {
            tagCell.tagListView.canRemoveTags = NO;
            [tagCell.tagListView.tags setArray:self.special];
            [tagCell.tagListView.collectionView reloadData];
            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                self.h3 = tagCell.tagListView.collectionView.contentSize.height;
            }
        }else if ([tagCell.titleLabel.text isEqualToString:@"喜欢"]){
            tagCell.tagListView.canRemoveTags = NO;
            [tagCell.tagListView.tags setArray:self.likeArr];
            [tagCell.tagListView.collectionView reloadData];
            if (tagCell.tagListView.collectionView.contentSize.height != 0) {
                self.h4 = tagCell.tagListView.collectionView.contentSize.height;
            }
        }else{
            
        }
        return tagCell;
    }
    
}
// UserVoiceViewControllerDelegate
- (void)changeVoice
{
    [self uploadingUserDataChange];
}
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [_pickview remove];
    _indexPath=indexPath;
    UserDataEditCell *cell = (UserDataEditCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
    
    if (indexPath.section == 0 ) {
        if (indexPath.row == 0 ){//昵称
            self.EditLabelVC.currentStr = cell.contentLabel.text;
            self.EditLabelVC.title = cell.titleLabel.text;
            [self.navigationController pushViewController:self.EditLabelVC animated:YES];
        }else if (indexPath.row == 1){
            _pickview=[[ZHPickView alloc] initDatePickWithDate:self.birthdayDate datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
            _pickview.delegate=self;
            [_pickview show];
        }else{
            _pickview=[[ZHPickView alloc] initPickviewWithPlistName:@"city" isHaveNavControler:NO];
            _pickview.delegate=self;
            [_pickview show];
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            self.EditLabelVC.currentStr = cell.contentLabel.text;
            self.EditLabelVC.title = cell.titleLabel.text;
            [self.navigationController pushViewController:self.EditLabelVC animated:YES];
        }else if (indexPath.row == 1){
            UserVoiceViewController *voiceController = [[UserVoiceViewController alloc]init];
            voiceController.voiceArray = self.voiceArray;
            voiceController.voiceFileArray = self.voiceFileArray;
            voiceController.delegate = self;
            [self.navigationController pushViewController:voiceController animated:YES];
        }else if (indexPath.row == 2){
            self.EditSeriesVC.title = cell.titleLabel.text;
            self.EditSeriesVC.nowSeriesStr = cell.contentLabel.text;
            if (self.currentUser.gender == 1) {
                self.EditSeriesVC.titleArr = @[@"小鲜肉系",@"高冷型男系",@"幽默逗比系",@"知心暖男系",@"霸道总裁系",@"百变全能系"];
            }else{
                self.EditSeriesVC.titleArr = @[@"软妹萝莉系",@"温柔依人系",@"阳光治愈系",@"知性御姐系",@"傲娇女王系",@"百变全能系"];
            }
            [self.EditSeriesVC.tableView reloadData];
            [self.navigationController pushViewController:self.EditSeriesVC animated:YES];
        }else if (indexPath.row == 3){
            NSArray *arr =@[@"宝贝", @"老婆", @"老公", @"欧巴", @"Baby", @"Dear", @"先生", @"Sweet", @"靓女", @"靓仔", @"帅锅",@"美女",@"宝宝",@"阿扎西",@"亲爱的",@"小姐"] ;
            [self pushTagsArr:arr NowtagsArr:self.salutationMeArr Title:cell.titleLabel.text maxTextCount:6 maxCount:8];
        }
    }else if (indexPath.section == 2){
        if (indexPath.row == 0) {
            NSArray *arr = @[@"你愿做我的初恋吗？",@"我感冒了，你会说什么？",@"世界上谁最漂亮？",@"如果我是一个虚拟人物，你想我是谁？",@"说出你最最肉麻的情话",@"你会主动向喜欢的人表白吗？",@"你怎么看待暧昧关系？",@"有人突然强吻你，你恰好也很喜欢ta，怎么办？",@"你最满意身上哪个部位？",@"为什么经常有人说，男人不坏，女人不爱？",@"用四个字形容你的长相"] ;
            [self pushTagsArr:arr NowtagsArr:[NSArray arrayWithObjects:self.currentUser.interestTopic?self.currentUser.interestTopic:@"", nil] Title:cell.titleLabel.text maxTextCount:40 maxCount:1];
        }else if (indexPath.row == 1) {
            NSArray *arr = @[@"结交新朋友",@"找个虚拟恋人",@"找到真爱",@"认真的谈一次恋爱",@"奔现"];
            [self pushTagsArr:arr NowtagsArr:self.wanArr Title:cell.titleLabel.text maxTextCount:6 maxCount:1];
        }else if (indexPath.row == 2) {
            NSArray *arr = @[@"180以上",@"幽默",@"小鲜肉",@"声音好听",@"唱歌好听",@"体贴人",@"长腿偶巴",@"长发飘飘高挑",@"童颜",@"浪漫",@"大胆说出爱",@"萌萌哒",@"娇小可爱",@"有马甲线",@"威武雄壮",@"干净",@"身材棒棒哒",@"成熟大叔",@"阳光暖男",@"有安全感"] ;
            [self pushTagsArr:arr NowtagsArr:self.idealArr Title:cell.titleLabel.text maxTextCount:6 maxCount:8];
        }else if (indexPath.row == 3) {
            NSArray *arr = @[@"为你唱歌",@"叫你起床",@"做你的树洞",@"逗你开心",@"陪你闲聊",@"哄你睡觉",@"陪你打游戏",@"做你的出气筒",@"陪你熬夜",@"随叫随到",@"给你正能量",@"温暖你",@"给你安全感",@"赞美你",@"安慰你",@"给你加油打气",@"为你疗伤",@"温柔体贴",@"开朗活泼",@"思想开放",@"豁达直率",@"诙谐风趣",@"声音甜美",@"声音俏皮",@"声音磁性",@"声音萌萌哒",@"聊星座",@"热剧吐槽",@"情感话题",@"讲故事",@"聊游戏",@"分享美食"] ;
            [self pushTagsArr:arr NowtagsArr:self.special Title:cell.titleLabel.text maxTextCount:6 maxCount:8];
        }else if (indexPath.row == 4){
            NSArray *arr = @[@"鹿晗", @"吴亦凡", @"LOL", @"陈奕迅", @"凤凰传奇", @"天天酷跑", @"火锅", @"海鲜", @"伦敦", @"饺子",@"沙县小吃",@"法国菜",@"手表",@"上海",@"香港",@"广州",@"北海道",@"伦敦",@"拉斯维加斯",@"北京",@"夏威夷群岛",@"Lady Gaga",@"AKB48",@"EXO",@"金秀贤",@"周杰伦",@"杨颖",@"Cf",@"DNF",@"我叫MT",@"魔兽世界"] ;
            [self pushTagsArr:arr NowtagsArr:self.likeArr Title:cell.titleLabel.text maxTextCount:6 maxCount:8];
        }
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            _pickview=[[ZHPickView alloc] initPickviewWithArray:@[@"圆球状",@"骨感",@"苗条",@"匀称",@"富态",@"丰满",@"健壮"] isHaveNavControler:NO];
            _pickview.delegate=self;
            [_pickview show];
        }else if (indexPath.row == 1){
            self.EditLabelVC.currentStr = cell.contentLabel.text;
            self.EditLabelVC.title = cell.titleLabel.text;
            [self.navigationController pushViewController:self.EditLabelVC animated:YES];
        }else if (indexPath.row == 2){
            NSArray *arr =@[@"普通话", @"广东话", @"上海话", @"湖南话", @"四川话", @"湖北话", @"英语", @"俄罗斯语", @"日语", @"韩语", @"德语", @"法语", @"五音不全"] ;
            [self pushTagsArr:arr NowtagsArr:self.languageArr Title:cell.titleLabel.text maxTextCount:6 maxCount:8];
        }
    }    
}


//section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.userInfoArr count];
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.userInfoArr objectAtIndex:section] count];
}


//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    
    if ([self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"职业"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"个人签名"]||[self.userInfoArr[indexPath.section][indexPath.row]isEqualToString:@"兴趣话题"]) {
        return [Utils LabeSizeLabelheight:self.userDataArr[indexPath.section][indexPath.row] Font:[UIFont fontWithName:FontName size:14]].height+(50-16.023438);
    }
    
    if (section == 2&&indexPath.row!=0){
        NSString *Title = self.userInfoArr[indexPath.section][indexPath.row];
        CGFloat height = 50;
        
        if ([Title isEqualToString:@"我想"]) {
            height = self.h1;
        }else if ([Title isEqualToString:@"理想的你"]){
             height = self.h2;
        }else if ([Title isEqualToString:@"特技"]){
            height = self.h3;
        }else if ([Title isEqualToString:@"喜欢"]){
             height = self.h4;
        }
        if (height <50) {
            return 50;
        }else{
            return height;
        }
        
    }else{
        return 50;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 80;
    }
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    return 10;
}

#pragma mark - tags delegate

//标签返回内容后赋值
-(void)UserTags:(NSArray *)Arr
{
    UserDataEditCell *cell = (UserDataEditCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
    
    NSString *CellTitle = cell.titleLabel.text;
    if ([CellTitle isEqualToString:@"喜欢"]){
        self.likeArr = Arr;
        UserDataEditTagCell *cell = (UserDataEditTagCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
        [cell.tagListView.tags setArray:self.likeArr];
        [cell.tagListView.collectionView reloadData];
        
        return;
    }else if ([CellTitle isEqualToString:@"语言"]){
        self.languageArr = Arr;
    }else if ([CellTitle isEqualToString:@"叫我"]){
        self.salutationMeArr = Arr;
    }else if ([CellTitle isEqualToString:@"兴趣话题"]){
        NSString *s = [Arr firstObject];
        if (s == nil) {
            s = @"";
        }
        self.interestTopic = s;
    }else if ([CellTitle isEqualToString:@"特技"]){
        
        self.special = Arr;
        UserDataEditTagCell *cell = (UserDataEditTagCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
        [cell.tagListView.tags setArray:self.special];
        [cell.tagListView.collectionView reloadData];
       
        return;
    }else if ([CellTitle isEqualToString:@"我想"]){
        self.wanArr = Arr;
        UserDataEditTagCell *cell = (UserDataEditTagCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
        [cell.tagListView.tags setArray:self.wanArr];
        [cell.tagListView.collectionView reloadData];
        return;
    }else if ([CellTitle isEqualToString:@"理想的你"]){
        self.idealArr = Arr;
        UserDataEditTagCell *cell = (UserDataEditTagCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
        [cell.tagListView.tags setArray:self.idealArr];
        [cell.tagListView.collectionView reloadData];
       
        return;
    }
    
    //标签数组转成字符串
    NSString *str = [[NSString alloc]init];
    for (int i = 0 ; i < Arr.count; i++) {
        if (i == Arr.count-1) {
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@",Arr[i]]];
        }else{
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@、",Arr[i]]];
        }
    }
   
    [self saveUserDataStr:str];
    
}

#pragma mark - private method

//修改文本返回内容后赋值
-(void)UserString:(NSString *)str
{
    [self saveUserDataStr:str];
}

//修改系列返回内容后赋值
-(void)UserSeriesString:(NSString *)str
{
    [self saveUserDataStr:str];
}

//暂存数据
-(void)saveUserDataStr:(NSString*)Str
{
    self.saveUserBool = YES;
    UserDataEditCell *cell = (UserDataEditCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
    cell.contentLabel.text = Str;
    //临时存储数据避免cell重用问题
    [self.userDataArr[_indexPath.section] replaceObjectAtIndex:_indexPath.row withObject:cell.contentLabel.text];
    [self userDataCompleteThedegree];
}

- (NSInteger)getUserPhoto
{
    NSInteger a =  self.userPhoto.Gallery.images.count;
    if (a<0) {
        a = 0;
    }
    if (a>8) {
        a = 8;
    }
    return  a;
}

- (NSInteger)getLoveSkill
{
    NSInteger a = 0;
    
    if ( self.salutationMeArr&&self.salutationMeArr.count) {
        a++;
    }
    
    if (self.voiceArray&&self.voiceArray.count) {
        a++;
    }
    return a;
}
- (BOOL)isNSString:(NSString *)str
{
    if (str&&str.length) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSDate:(NSDate *)date
{
    if (date) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSArray:(NSArray *)arr
{
    if (arr&&arr.count) {
        return YES;
    }
    return NO;
}
//资料完整度
-(void)userDataCompleteThedegree{
    
    __block NSInteger completenessValue = 100;
    MLUser *u = [MLUser currentUser];
    __block  NSInteger a = 0;
    //个人资料
    //昵称
    [self isNSString:self.userDataArr[0][0]]==YES?a++:a;
    //生日
    [self isNSDate:self.birthdayDate]==YES?a++:a;
    //城市
    [self isNSString:self.location_city]==YES?a++:a;
    //个人签名
    [self isNSString:self.userDataArr[1][0]]==YES?a++:a;
    //声线
    u.isHasVoice==YES?a++:a;
    //属于
    [self isNSString:self.userDataArr[1][2]]==YES?a++:a;
    //喜欢
    [self isNSArray:self.likeArr]==YES?a++:a;
    //叫我
    [self isNSArray:self.salutationMeArr]==YES?a++:a;
    //外貌
    [self isNSString:self.figure]==YES?a++:a;
    //职业
    [self isNSString:self.userDataArr[3][1]]==YES?a++:a;
    //语言
    [self isNSArray:self.languageArr]==YES?a++:a;
    //特技
    [self isNSArray:self.special]==YES?a++:a;
    //兴趣话题
    [self isNSString:self.interestTopic]==YES?a++:a;
    //我想
    [self isNSArray:self.wanArr]==YES?a++:a;
    //理想的你
    [self isNSArray:self.idealArr]==YES?a++:a;
    
    a = a+self.myGallery.images.count;
    completenessValue = completenessValue - (23-a)*4;
    //保存资料完整度
    [Utils saveUserDataIntegrityNumber:completenessValue];
    
    UILabel *completeness = (UILabel *)[self.view viewWithTag:200];
    UIView *Line2 = (UIView *)[self.view viewWithTag:101];
    completeness.text = [NSString stringWithFormat:@"%ld%% ",(long)completenessValue];
    [Utils animationMobileTimer:5 View:Line2 Rect:CGRectMake(0, 0, (DeviceWidth-150)*completenessValue/100, 10)];
    
}

//push标签页面
-(void)pushTagsArr:(NSArray*)tagsArr NowtagsArr:(NSArray*)nowtagsArr Title:(NSString*)title maxTextCount:(NSInteger)maxTextCount maxCount:(NSInteger)maxCount;
{
    if (maxTextCount == 0) {
        maxTextCount = 6;
    }
    if (maxCount == 0) {
        maxCount = 8;
    }
    UserTagsViewController *tagsVC = [[UserTagsViewController alloc] init];
    tagsVC.tags = tagsArr;
    tagsVC.maxTextCount = maxTextCount;
    tagsVC.maxCount = maxCount;
    tagsVC.title = title;
    tagsVC.Delegate = self;
    [tagsVC nowTagsAr:nowtagsArr];
    [self.navigationController pushViewController:tagsVC animated:YES];
}

//选择控件返回内容后赋值
-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(id )resultString{
    NSString * str = [[NSString alloc]init];
    //地址需要拼接
    if ([resultString isKindOfClass:[NSArray class]]) {
        if (_indexPath.row == 2) {
            self.location_province = resultString[0];
            self.location_city = resultString[1];
        }
        [self saveUserDataStr:resultString[1]];
        //时间格式转字符串
    }else if ([resultString isKindOfClass:[NSDate class]]){
        self.birthdayDate = resultString;
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        str = [dateFormatter stringFromDate:resultString];
        [self saveUserDataStr:str];
        
    }else if (_indexPath.section == 3&&_indexPath.row == 0){
        self.figure = resultString;
        [self saveUserDataStr:resultString];
    }
    else{
        //其他正常
        [self saveUserDataStr:resultString];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark - voice

- (void)initAudioReader {
    // 初始化音频播放器
    MLAudioPlayer *player = [[MLAudioPlayer alloc]init];
    AmrPlayerReader *amrReader = [[AmrPlayerReader alloc]init];
    player.fileReaderDelegate = amrReader;
    
    self.player = player;
    self.amrReader = amrReader;
}

- (void)playVoice:(UIButton *)sender {
    if ([self.player isPlaying]) {
        [self.player stopPlaying];
        // 停止计时器
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
        [sender setImage:[UIImage imageNamed:@"voice_play_3"] forState:UIControlStateNormal];
    }
    self.amrReader.filePath = self.voiceFileArray[0];
    self.voicePlayIndex = sender.tag;
    self.voicePlayStatus = 3;
    [self.player startPlaying];
    self.updateAudioUITimer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(updateVoiceBtnUI) userInfo:nil repeats:YES];
}

- (void)updateVoiceBtnUI {
    // 更新播放按钮显示
    VoiceCell *cell = (VoiceCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
    if ([self.player isPlaying]) {
        // 更新图片显示
        if (3 == self.voicePlayStatus) {
            self.voicePlayStatus = 1;
        } else {
            self.voicePlayStatus++;
        }
        NSString *bgImgName = [NSString stringWithFormat:@"voice_play_%ld", (long)self.voicePlayStatus];
        [cell.voiceBtn setImage:[UIImage imageNamed:bgImgName] forState:UIControlStateNormal];
    } else {
        // 播放结束, 停止计时器
        [self.updateAudioUITimer invalidate];
        self.updateAudioUITimer = nil;
        
        [cell.voiceBtn setImage:[UIImage imageNamed:@"voice_play_3"] forState:UIControlStateNormal];
    }
}

@end